﻿using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Command.Material_Management
{
    public class AddProductMaterialsHander : IRequestHandler<AddProductMaterialsCommand, ApiResult<int>>
    {
        private readonly IRepository<ProductMaterialsModel> productMaterialsRepo;
        private readonly IMapper mapper;
        public AddProductMaterialsHander(IRepository<ProductMaterialsModel> productMaterialsRepo, IMapper mapper)
        {
            this.productMaterialsRepo = productMaterialsRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加产品物料
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddProductMaterialsCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            //产品物料编码不能重复
            var exists = productMaterialsRepo.GetAll().Where(a => a.ProductMaterialsCode == request.ProductMaterialsCode).FirstOrDefault();
            if (exists != null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "该产品物料编码已存在，请重新输入！";
                return await Task.FromResult(result);
            }
            var model = mapper.Map<ProductMaterialsModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateTime = DateTime.Now;
            model.IsDel = false;
            if (model != null)
            {
                await productMaterialsRepo.AddAsync(model);
                result.Code = StatusCode.Success;
                result.Message = "添加成功！";
                return await Task.FromResult(result);
            }
            else
            {
                result.Code = StatusCode.Fail;
                result.Message = "添加失败！";
                return await Task.FromResult(result);
            }
        }
    }
}
